﻿/**********************************************
 * 功能名称：作业成本分配路径选择界面
编写人：  杨莹
建立时间： 杨 2008年11月19日
说明：
加载页面时，列出作业中心树型目录
将当前作业中心的目标中心，显示为checked
可点击相应的树结点，
选择一个作业动因ID。
选中后提交：删除全部已有目标中心，再插入所有刚选择的作业中心,
 * 本页使用了LINQ的事务处理方法。
 **************************************************************/
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Hisun.Models;
using System.Data.Linq;
using System.Collections.Generic;





namespace Hisun.View.CostCenterPath
{
    public partial class CostCenterSelect : AbcPageBase
    {
        HisunDBDataContext db = new HisunDBDataContext();


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {




          
                    //将从发送页的当前作业中心ID保存到本页

                    TextBox_ID.Text = Request.QueryString["centerid"].ToString();
                    int myid = Convert.ToInt32(TextBox_ID.Text);
                    //查询出当前作业中心ID对应的作业中心名称
                    var myquery = (from a in db.TABC_JS_CostCenter where a.作业中心ID == myid select a).Single();
                    TextBox_Name.Text = myquery.作业中心名称;
                    var myquery2 = (from b in db.TABC_JS_CostCenterPathFramework
                                   where b.作业中心ID == myid
                                   select b.成本动因ID).Distinct();

                    if (myquery2.Count() == 1)
                    {
                        var myquery3 = from c in db.TABC_DM_CostDivers
                                       where c.成本动因ID == myquery2.Single()
                                       select c.成本动因ID;
                        if (myquery3.Count() == 1)
                        {
                            DropDownList_CostDriver.SelectedValue = myquery3.Single().ToString();
                        }
                    
                    }


                    //j生成作业中心树，当前作业中心对应的目标中心应显示为checked 
                    CreateTree();


            }
        }

        private bool isGoalid(int Centerid)
        {
            int myid = Convert.ToInt32(TextBox_ID.Text);

            var Goalids = (from b in db.TABC_JS_CostCenterPathFramework where b.作业中心ID == myid select b.目标中心ID).ToList();

            if (Goalids.Contains(Centerid))
            {
                return true;
            }
            else
            {
                return false;
            }


        }

        #region 生成作业中心目录数
        private void MakeMenu(TABC_JS_CostCenter[] menuSource)
        {
            foreach (var node in menuSource)
            {
                // 创建父节点
                if (node.上级作业中心ID == 0)
                {
                    TreeNode newNode = new TreeNode(node.作业中心名称, node.作业中心ID.ToString());
                    // newNode.NavigateUrl = node.页面文件;
                    int myid = node.作业中心ID;
                    if (isGoalid(myid))
                    { newNode.Checked = true; }
                    else
                    { newNode.Checked = false; }
      
                    this.TreeView_GoalCenter.Nodes.Add(newNode);


                    GenerateSubMenu(GetSubNodeSource(node, menuSource), newNode, menuSource);
                }
            }
            TreeView_GoalCenter.ExpandAll();
        }


        /// <summary>
        /// 产生子节点
        /// </summary>
        /// <param name="childNodes"></param>
        /// <param name="fatherNode"></param>
        /// <param name="menuSource"></param>
        private void GenerateSubMenu(TABC_JS_CostCenter[] childNodes, TreeNode fatherNode, TABC_JS_CostCenter[] menuSource)
        {
            foreach (TABC_JS_CostCenter node in childNodes)
            {
                TreeNode newNode = new TreeNode(node.作业中心名称, node.作业中心ID.ToString());
                int myid = node.作业中心ID;
                if (isGoalid(myid))
                { newNode.Checked = true; }
                else
                { newNode.Checked = false; }
                fatherNode.ChildNodes.Add(newNode);

                GenerateSubMenu(GetSubNodeSource(node, menuSource), newNode, menuSource);
            }
        }
        /// <summary>
        /// 产生子节点的数据源
        /// </summary>
        /// <param name="father"></param>
        /// <param name="menuSource"></param>
        /// <returns></returns>
        private TABC_JS_CostCenter[] GetSubNodeSource(TABC_JS_CostCenter father, TABC_JS_CostCenter[] menuSource)
        {
            List<TABC_JS_CostCenter> subNodesSource = new List<TABC_JS_CostCenter>();
            foreach (TABC_JS_CostCenter node in menuSource)
            {
                //if (father.是否末级 == 'T')
                //{
                //    break;
                //}
                //else
                //{
                if (node.上级作业中心ID == father.作业中心ID)
                {
                    subNodesSource.Add(node);
                }
                //}
            }
            return subNodesSource.ToArray();
        }
        #endregion

        private void CreateTree()
        {
            var MyCenterTree = (from a in db.TABC_JS_CostCenter select a).ToArray();
            this.TreeView_GoalCenter.Nodes.Clear();
            MakeMenu(MyCenterTree);
            TreeView_GoalCenter.ExpandAll();



        }

        protected void Button_Save_Click(object sender, EventArgs e)
        {

            if (!Page.IsValid)
            {

                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "message", " <script>alert('成本动因为空'); </script>");

            }

            if (TreeView_GoalCenter.CheckedNodes.Count == 0)
            {
                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "message", " <script>alert('请选择一个或多个目标作业中心'); </script>");


            }
            else
            {
                int MyCenterId = Convert.ToInt32(TextBox_ID.Text);

                //事务处理代码阶段
               if (db.Connection != null) db.Connection.Open();
                System.Data.Common.DbTransaction tran = db.Connection.BeginTransaction();
                db.Transaction = tran;

                var mydel = from a in db.TABC_JS_CostCenterPathFramework where a.作业中心ID == MyCenterId select a;


                try
                {
                    db.TABC_JS_CostCenterPathFramework.DeleteAllOnSubmit(mydel);
                    db.SubmitChanges();

                    foreach (TreeNode trNode in TreeView_GoalCenter.CheckedNodes)
                    {
                        TABC_JS_CostCenterPathFramework myrow = new TABC_JS_CostCenterPathFramework();
                        myrow.公司ID = "hisun";
                        myrow.账套ID = "001";
                        myrow.作业中心ID = MyCenterId;
                        myrow.录入人 = Session[ServerVars.sysSessionUserName].ToString();
                        myrow.目标中心ID = Convert.ToInt32(trNode.Value);
                        myrow.成本动因ID = Convert.ToInt32(DropDownList_CostDriver.SelectedValue);

                        db.TABC_JS_CostCenterPathFramework.InsertOnSubmit(myrow);

                    }

                    db.SubmitChanges();
                    tran.Commit();

                }
                catch
                {
                    tran.Rollback();
                }
                finally
                {
                  //  Server.Transfer("~/View/CostCenterPath/CostCenterPathSetup.aspx");
                    Response.Write("<script>history.go(-2);</script>");
                }
            }
        }

        protected void Button_Cancel_Command(object sender, CommandEventArgs e)
        {
            //Server.Transfer("~/View/CostCenterPath/CostCenterPathSetup.aspx");
            Response.Write("<script>history.go(-2);</script>");
        }



    }
}
